<?php

namespace App\Http\Controllers\Innerend;


use App\Models\ArticleComment;
use App\Models\News;
use App\Models\NewsCate;
use App\Models\NewsDesc;
use App\Models\NewsTopic;
use App\Models\SiteCate;
use App\Models\Topic;
use App\Models\TopicCate;
use App\Models\User;
use App\Service\Tree;
use Illuminate\Support\Facades\DB;

class NewsController extends BaseController
{
    // 新闻文章

    protected $list_cache = true;

    public function initialize()
    {
        parent::initialize();

        $this->model = 'news';
    }

    // 父级
    // 添加，修改，删除，列表，停用 操作

    // 列表数据展示
    protected function listTable($lists)
    {
        // 整理
        $trList = [];
        if(empty($lists)){
            return ['list' => $lists, 'tr' => $trList];
        }

        $userDb = new User();
        $uids   = array_column($lists, 'uid');
        $users  = $userDb->isCache(true)->getListInIds($uids);

        // 展示列表表格
        $listHtml = $this->adminList();
        foreach($lists as $key => $item){
            // 数据
            $_uid  = $item['uid'];
            $_user = $users[$_uid] ?? [];
            $_id   = $item['id'];
            //$status   = $item['status'] == 1 ? '正常' : '禁用';
            $topOp  = $item['is_top'] == 1 ? '取消置顶' : '置顶';
            $is_top = $item['is_top'] == 1 ? '是' : '否';
            $param  = ['id' => $_id, 'is_top' => 1 - $item['is_top']];
            // 操作
            $operate = $listHtml->operate_status($param, $topOp, $item['is_top'], 'to-top');
            $operate .= $listHtml->operate_edit(['id' => $_id], '编辑');
            $operate .= $listHtml->operate_soft_delete(['id' => $_id], '你确定要删除该文章吗？');

            // 页面
            $tr = $listHtml->list_check($item['id']);
            $tr .= $listHtml->list_td($item['title']);
            $tr .= $listHtml->list_td($_user['username']);
            //$tr .= $listHtml->list_td($item['author']);
            $tr .= $listHtml->list_td($item['original']);
            $tr .= $listHtml->list_td($is_top);
            $tr .= $listHtml->list_td(date('Y-m-d H:i', $item['ctime']));
            $tr .= $listHtml->list_td($operate);
            $tr .= $operate;

            // 整合
            $trList[] = $listHtml->list_tr($tr);
        }

        // 整合
        return ['list' => $lists, 'tr' => $trList];
    }

    // 列表字段
    protected function list_fields()
    {
        // 'author' => '作家',
        return ['title' => '标题', 'uid' => ['用户', 80],  'original' => ['来源',120], 'is_top' => ['是否置顶', 60], 'ctime' => ['创建时间', 120], 'operate' => ['操作', 250],];
    }

    // 软删除
    public function onSoft()
    {
        $this->throwIf(empty($this->id), '请指定删除记录');

        $where  = ['id' => $this->id];
        $model  = $this->checkModel($this->model);
        $result = $model->isCache(true)->softDelete($where);
        $this->throwIf($result === false, $model->getError());

        return $this->success();
    }

    // 列表搜索
    protected function list_search()
    {
        $cateDb = new SiteCate();
        $cates  = $cateDb->isCache(true)->getList(['status' => 1]);
        $tops   = [0 => '未置顶', 1 => '置顶'];

        $request = $this->getData();
        $form    = $this->adminList();
        $keyword = $form->formInput('keyword', $request['keyword'] ?? '', '关键字');
        $cate_id = $form->formSelectLists('cate_id', $request['cate_id'] ?? '0', $cates, 'id', 'title');
        $is_top  = $form->formSelect('is_top', $request['is_top'] ?? null, $tops);

        $search = ['keyword' => $keyword, 'is_top' => $is_top,];  // 'cate_id' => $cate_id
        $this->assign('search', $search);

        $searchHide = ['channel'];
        $this->assign('searchHide', []);
    }


    // 表单页面
    protected function formTable()
    {
        $html = '';
        $info = $this->onShow();
        $form = $this->adminForm();

        // 多个图片
        // TODO 默认一张图片
        /*$images = '';
        foreach($_images as $key => $image){
            //$images .= $form->formShowImage($image);
            $images .= $form->formImage('images['.$key.']', $image);
        }*/
        // TODO 默认一张图片
        $images = $form->formImage('images', $_images[0] ?? '');

        $cate_id  = $form->ajaxSearchList('cate_id', $info['cate'], 'Cate', 'id', 'title');
        $topic_id = $form->ajaxSearchList('topic_id', $info['topic'], 'Topic', 'id', 'title');

        $username    = $form->ajaxSearch('uid', $info['uid'] ?? '', 'User');
        $is_top      = $form->formRadio('is_top', $info['is_top'] ?? 1, [1 => '置顶', 0 => '不置顶']);
        $title       = $form->formInput('title', $info['title'] ?? '', '标题');
        $author      = $form->formInput('author', $info['author'] ?? '', '作家');
        $original    = $form->formInput('original', $info['original'] ?? '', '来源');
        $description = $form->formTextarea('description', $info['description'] ?? '');
        $content     = $form->formUeditor('content', $info['content'] ?? '');
        $_id         = $form->formHidden('id', $info['id'] ?? '');

        $html .= $form->makeItem('标题', $title);
        $html .= $form->makeItem('编辑', $username);
        $html .= $form->makeItem('栏目', $cate_id);
        $html .= $form->makeItem('话题', $topic_id);
        $html .= $form->makeItem('作家', $author);
        $html .= $form->makeItem('来源', $original);
        //$html .= $form->makeItem('图片', $images);
        $html .= $form->makeItem('是否置顶', $is_top);
        $html .= $form->makeItem('描述', $description);
        $html .= $form->makeItem('内容', $content);
        $html .= $_id;

        return $html;
    }

    // 以前的
    protected function formTable2()
    {
        $html = '';
        $info = $this->onShow();
        $form = $this->adminForm();

        // 默认三个栏目
        if(empty($info['cate_ids'])){
            $info['cate_ids'] = ['', '', ''];
        } else{
            $count = count($info['cate_ids']);
            for($ii = 0; $ii < 3 - $count; $ii++){
                $info['cate_ids'][] = '';
            }
        }

        // 默认三个话题
        if(empty($info['topic_ids'])){
            $info['topic_ids'] = ['', '', ''];
        } else{
            $count = count($info['topic_ids']);
            for($ii = 0; $ii < 3 - $count; $ii++){
                $info['topic_ids'][] = '';
            }
        }
        // TODO 默认一张图片
        if(empty($info['images'])){
            $_images = ["", "", ""];
        } else{
            $_images = json_decode($info['images'], true);
            $count   = count($_images);
            for($ii = 0; $ii < 3 - $count; $ii++){
                $_images[] = '';
            }
        }

        // 多个栏目
        $cateDb = new SiteCate();
        $cates  = $cateDb->isCache(true)->getList(['status' => 1]);
        $cates  = (new Tree())->toList($cates); // 树状
        $cate   = '';
        foreach($info['cate_ids'] as $key => $cateId){
            $cate .= $form->formSelectLists('cate_id[]', $cateId, $cates, 'id', 'title');
        }

        // 多个话题
        $topicDb = new Topic();
        $topics  = $topicDb->isCache(true)->getList(['status' => 1, 'verify' => 1,]);
        $topic   = '';
        foreach($info['topic_ids'] as $key => $topicId){
            $topic .= $form->formSelectLists('topic_id[]', $topicId, $topics, 'id', 'title');
        }


        // 多个图片
        // TODO 默认一张图片
        /*$images = '';
        foreach($_images as $key => $image){
            //$images .= $form->formShowImage($image);
            $images .= $form->formImage('images['.$key.']', $image);
        }*/
        // TODO 默认一张图片
        $images = $form->formImage('images', $_images[0] ?? '');

        $username    = $form->ajaxSearch('uid', $info['uid'] ?? '', 'User');
        $is_top      = $form->formRadio('is_top', $info['is_top'] ?? 1, [1 => '置顶', 0 => '不置顶']);
        $title       = $form->formInput('title', $info['title'] ?? '', '标题');
        $author      = $form->formInput('author', $info['author'] ?? '', '作家');
        $original    = $form->formInput('original', $info['original'] ?? '', '来源');
        $description = $form->formTextarea('description', $info['description'] ?? '');
        $content     = $form->formUeditor('content', $info['content'] ?? '');
        $_id         = $form->formHidden('id', $info['id'] ?? '');

        $html .= $form->makeItem('标题', $title);
        $html .= $form->makeItem('编辑', $username);
        $html .= $form->makeItem('栏目', $cate);
        $html .= $form->makeItem('话题', $topic);
        $html .= $form->makeItem('作家', $author);
        $html .= $form->makeItem('来源', $original);
        $html .= $form->makeItem('图片', $images);
        $html .= $form->makeItem('是否置顶', $is_top);
        $html .= $form->makeItem('描述', $description);
        $html .= $form->makeItem('内容', $content);
        $html .= $_id;

        return $html;
    }

    // 置顶操作
    public function toTop()
    {
        $is_top = $this->getData("is_top", 0, 'intval');
        $id     = $this->getData("id", 0, 'intval');
        $this->throwReturn(empty($id), '请选择需要修改的数据！');
        $this->throwReturn(!in_array($is_top, [0, 1]), '请选择正确置顶状态！');

        // 查询数据
        $model = new News();
        $info  = $model->isCache(true)->getOneById($id);
        if(empty($info)){
            return $this->error('你要操作的数据不存在！！');
        }


        DB::beginTransaction();
        try{
            // 删除文章附件，属性，日志，评论
            $model->where('id', $id)->update(['is_top' => $is_top]);

            DB::commit();
        } catch(\Exception $e){
            DB::rollBack();

            return $this->error($e->getMessage());
        }

        // 缓存操作
        $model->deleteCacheShow($info);
        $model->deleteCacheShow(['id' => $id, 'is_top' => $is_top]);

        return $this->success();
    }

    // 置顶操作
    public function toTops()
    {
        $is_top = $this->getData("is_top", 0, 'intval');
        $ids    = $this->getData("ids", [], 'is_array');
        $this->throwReturn(empty($ids), '请选择需要修改的数据！');
        $this->throwReturn(!in_array($is_top, [0, 1]), '请选择正确置顶状态！');
        $this->throwReturn(count($ids) != count($ids, 1), '请选择正确id数据！');

        // 查询数据
        $model = new News();
        $lists = $model->isCache(true)->getListInIds($ids);
        if(empty($lists)){
            return $this->error('你要操作的数据不存在！！');
        }

        $_ids = array_column($lists, 'id');
        DB::beginTransaction();
        try{
            // 删除文章附件，属性，日志，评论
            $model->whereIn('id', $_ids)->update(['is_top' => $is_top]);

            DB::commit();
        } catch(\Exception $e){
            DB::rollBack();

            return $this->error($e->getMessage());
        }

        // 缓存操作
        $model->deleteCacheList($lists);
        $model->deleteCacheShow(['id' => $_ids, 'is_top' => $is_top]);

        return $this->success();
    }

    // 删除（软删除）
    public function del()
    {
        $this->throwIf(empty($this->id), '请指定删除记录');

        $where  = ['id' => $this->id];
        $model  = $this->checkModel($this->model);
        $result = $model->isCache(true)->softDelete($where, ['verify' => -1]);
        $this->throwIf($result === false, $model->getError());

        return $this->success();
    }

    // 删除（软删除）
    public function delComment()
    {
        $ids = $this->getData('ids', [], 'is_array');
        $this->throwIf(empty($ids), '请指定删除记录!');
        $this->throwIf(count($ids) != count($ids, 1), '指定删除记录参数错误!');
        // 其他条件
        $news_id = $this->getData('news_id', 0, 'intval');
        $where   = ['channel' => 'news', 'article_id' => $news_id];
        $this->throwIf(empty($news_id), '请指定新闻文章编号!');

        $comment = new ArticleComment();
        $result  = $comment->isCache(true)->softDelete($where, $ids);
        $this->throwIf($result === false, $comment->getError());

        return $this->success();
    }

    // 查找
    public function _show()
    {
        $this->throwIf(empty($this->id), '请指定查看记录');

        $where = [['id', '=', $this->id], ['verify', '=', 1]];
        $model = $this->checkModel($this->model);
        $info  = $model->isCache(true)->oneFind($where);
        $this->throwIf($info === false, $model->getError());

        // 查找用户信息
        if($info['uid']){
            $uid    = $info['uid'];
            $userDb = new User();
            $types  = $this->userType(); // 认证类型
            // $user   = $userDb->isCache(true)->getListInIds([$uid]);
            $user = $userDb->isCache(true)->getOneById($uid);
            if($user){
                // $user               = $user[$uid];
                $user['head_img']   = $this->getHeadImg($user['head_img'] ?? '');
                $user['apply_type'] = $user['is_apply'] == 1 ? ($types[$user['apply_type']]['name'] ?? '') : '';
                // $user['apply_type'] = $types[$user['apply_type']]['name'] ?? '';
            }
            $info['user'] = $user;
        }

        return $this->success($info);
    }

    // 快讯的评论
    public function comment()
    {
        $this->throwIf(empty($this->id), '请指定查看记录');
        $where   = ['article_id' => $this->id, 'channel' => 'news', 'verify' => 1]; // 'pid' => 0,
        $comment = new ArticleComment();
        $result  = $comment->listPage($where, $this->page, $this->rows);
        if($result['list']){
            $uids   = array_column($result['list'], 'uid');
            $userDb = new User();
            $types  = $this->userType(); // 认证类型
            $users  = $userDb->isCache(true)->getListInIds($uids);
            foreach($result['list'] as $key => $item){
                $_uid  = $item['uid'];
                $_info = $users[$_uid] ?? [];
                if($_info){
                    $_info['head_img']   = $this->getHeadImg($_info['head_img'] ?? '');
                    $_info['apply_type'] = $_info['is_apply'] == 1 ? ($types[$_info['apply_type']]['name'] ?? '') : '';
                    // $_info['apply_type'] = $types[$_info['apply_type']]['name'] ?? '';
                }

                // 整理
                $result['list'][$key]['user']       = $_info;
                $result['list'][$key]['apply_type'] = $item['is_apply'] == 1 ? ($types[$item['apply_type']]['name'] ?? '') : '';
                // $result['list'][$key]['apply_type'] = $types[$item['apply_type']]['name'] ?? '';
            }
        }

        return $this->success($result);
    }

    // 列表查询
    protected function listWhere()
    {
        $where   = [['verify', '=', 1]];
        $is_top  = $this->getData("is_top", null, 'intval');
        $keyword = $this->getData('keyword', null, 'trim');
        if($keyword){
            $where[] = ['content', 'like', $keyword];
            // 不在缓存
            $this->list_cache = false;
        }
        if(!is_null($is_top)){
            $where[] = ['is_top', '=', $is_top];
        }

        return $where;
    }

    // 添加
    protected function _before_add()
    {
        $ip   = $this->request->ip();
        $data = [
            // 'id'          => $this->getData("id"),
            'title'       => $this->getData("title", null, 'trim'),
            'uid'         => $this->getData("uid", 1, 'intval'),
            //'pic'         => $this->getData("pic", null, 'trim'),
            'original'    => $this->getData("original", null, 'trim'),
            'is_original' => $this->getData("is_original", 0, 'intval'),
            'keyword'     => $this->getData("keyword", null, 'trim'),
            'description' => $this->getData("description", null, 'trim'),
            'author'      => $this->getData("author", null, 'trim'),
            'ip'          => $ip,
            'ip_address'  => $this->getIpAddress($ip),
            'is_top'      => $this->getData("is_top", 0, 'intval'),
            'is_draft'    => $this->getData("is_draft", 0, 'intval'),

            // 详情
            // 'images'   => $this->getData("images", null, 'trim'),
            // 'news_id'  => $this->getData("news_id", 0, 'intval'),
            // 'verify'   => $this->getData("verify", 0, 'intval'),
            'verify'      => 1,
            'describe'    => $this->getData("describe", null, 'trim'),
            'content'     => $this->getData("content", null, 'trim'),
            // 其他
            'topic_ids'   => $this->getData("topic_id", null, 'is_array'),
            'cate_ids'    => $this->getData("cate_id", null, 'is_array'),
            'nickname'    => $this->myUser['nickname'] ?: $this->myUser['username'],
            'adminId'     => $this->myUser['id'],

            // 'has_pic'     => $this->getData("has_pic", 0, 'intval'),
            // 'cate_id'     => $this->getData("cate_id", 0, 'intval'),
            // 'old_classid' => $this->getData("old_classid", 0, 'intval'),
            // 'read_no'     => $this->getData("read_no", 0, 'intval'),
            // 'virtual_no'  => $this->getData("virtual_no", 0, 'intval'),
            // 'comment_no'  => $this->getData("comment_no", 0, 'intval'),
            // 'praise_no'   => $this->getData("praise_no", 0, 'intval'),
            // 'collect_no'  => $this->getData("collect_no", 0, 'intval'),
            // 'relay_no'    => $this->getData("relay_no", 0, 'intval'),
            // 'ctime'       => $this->getData("ctime", 0, 'intval'),
            // 'mtime'       => $this->getData("mtime", 0, 'intval'),
        ];

        $this->throwIf(empty($data['uid']), '请选择发布的用户!');
        // TODO 审核
        $this->baiduTextCensor($data);
        // TODO 提取图片
        //$images = $this->getData("images", null, 'is_array');
        $images = $this->getData("images");
        if(empty($images)){
            $images = $this->getImage4content($data['content']);
        } else{
            $images = is_array($images) ? $images : [$images];
        }
        $data['images'] = json_encode($images);

        return $data;
    }

    // 修改
    protected function _before_edit()
    {
        $data = [
            'title'       => $this->getData("title", null, 'trim'),
            'uid'         => $this->getData("uid", 1, 'intval'),
            //'pic'         => $this->getData("pic", null, 'trim'),
            'original'    => $this->getData("original", null, 'trim'),
            'is_original' => $this->getData("is_original", 0, 'intval'),
            'keyword'     => $this->getData("keyword", null, 'trim'),
            'description' => $this->getData("description", null, 'trim'),
            'author'      => $this->getData("author", null, 'trim'),
            'ip'          => $this->request->ip(),
            'is_top'      => $this->getData("is_top", 0, 'intval'),
            'is_draft'    => $this->getData("is_draft", 0, 'intval'),

            // 详情
            //'images'    => $this->getData("images", null, 'trim'),
            // 'news_id'  => $this->getData("news_id", 0, 'intval'),
            // 'verify'   => $this->getData("verify", 0, 'intval'),
            'verify'      => 1,
            'describe'    => $this->getData("describe", null, 'trim'),
            'content'     => $this->getData("content", null, 'trim'),
            // 其他
            'topic_ids'   => $this->getData("topic_id", [], 'json_decode'),
            'cate_ids'    => $this->getData("cate_id", [], 'json_decode'),
            'nickname'    => $this->myUser['nickname'] ?: $this->myUser['username'],
            'adminId'     => $this->myUser['id'],
        ];


        $this->throwIf(empty($data['uid']), '请选择发布的用户!');
        // TODO 审核
        $this->baiduTextCensor($data);

        // TODO 提取图片
        //$images = $this->getData("images", null, 'is_array');
        $images = $this->getData("images");
        if(empty($images)){
            $images = $this->getImage4content($data['content']);
        } else{
            $images = is_array($images) ? $images : [$images];
        }
        $data['images'] = json_encode($images);

        return $data;
    }

}


